package com.example.wuqiu.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wuqiu.common.enums.DictCode;
import com.example.wuqiu.common.QueryField;
import com.example.wuqiu.module.sys.dao.SysOrganMapper;
import com.example.wuqiu.module.sys.entity.SysOrgan;
import com.example.wuqiu.module.sys.entity.SysUser;
import com.example.wuqiu.module.sys.entity.SysUserOrgan;
import com.example.wuqiu.module.sys.service.SysOrganService;
import com.example.wuqiu.module.sys.service.SysUserOrganService;
import com.example.wuqiu.module.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author RedStar
 * @since 2023-02-05
 */
@Service
public class SysOrganServiceImpl extends ServiceImpl<SysOrganMapper, SysOrgan> implements SysOrganService {
    @Resource
    private SysUserOrganService sysUserOrganService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysOrganMapper sysOrganMapper;

    private List<SysUser> sysUserList = new ArrayList<>();

    @Override
    public LambdaQueryWrapper<SysOrgan> createQueryWrapper(SysOrgan param) {
        LambdaQueryWrapper<SysOrgan> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(param.getParentId())) {
            queryWrapper.eq(SysOrgan::getParentId, param.getParentId());
        }
        if (StringUtils.isNotBlank(param.getName())) {
            queryWrapper.like(SysOrgan::getName, param.getName());
        }

        /**/
        if (param.getStatus() != null) {
            queryWrapper.eq(SysOrgan::getStatus, param.getStatus());
        } else {
//            queryWrapper.eq(SysOrgan::getStatus, QueryField.STATU_NOR);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getOrderBy())) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getOrderByType())
                    && QueryField.ASC.equals(param.getOrderByType())) {
                queryWrapper.orderByAsc(SysOrgan::getStatus);
            } else {
                queryWrapper.orderByDesc(SysOrgan::getOrderBy);
            }
        } else {
            queryWrapper.orderByAsc(SysOrgan::getSort);
        }
        return queryWrapper;
    }
    @Override
    public List<SysOrgan> getTreeAll(SysUser loginUser) {
        // 获取所有
        LambdaQueryWrapper<SysOrgan> queryWrapper = new LambdaQueryWrapper<>();

        List<String> roleIdList = loginUser.getRoleIdList();
        //不是管理员
        if (!roleIdList.contains(DictCode.ADMIN.dictValue)) {
            List<String> topIdChilds = getTopIdChilds(getTopIds(loginUser.getOrganIdList()));
            if (!ListUtils.isEmpty(topIdChilds)) {
                queryWrapper.in(SysOrgan::getId, topIdChilds);
            }
        }

        queryWrapper.eq(SysOrgan::getStatus, QueryField.STATU_NOR_);

        List<SysOrgan> organList = list(queryWrapper);
        List<SysOrgan> collect = organList.stream().sorted(Comparator.comparing(SysOrgan::getSort,Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());

        List<SysOrgan> menus = buildTree(collect);
        return menus;
    }

    @Override
    public List<SysOrgan> getTreeAllAndUser(SysUser loginUser) {
        // 获取所有
        LambdaQueryWrapper<SysOrgan> queryWrapper = new LambdaQueryWrapper<>();

        List<String> roleIdList = loginUser.getRoleIdList();

        List<SysOrgan> sysMenus = new ArrayList<>();
        //不是管理员
        if (!roleIdList.contains(DictCode.ADMIN.dictValue)) {
            List<String> topIdChilds = getIdChilds(loginUser.getOrganIdList());
            if (!ListUtils.isEmpty(topIdChilds)) {
                queryWrapper.in(SysOrgan::getId, topIdChilds);
                sysMenus = list(queryWrapper);
            }

            topIdChilds = getTopIdChilds(loginUser.getOrganIdList());
            LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = sysUserService.createQueryWrapper(new SysUser().setOrganIdList(topIdChilds));
            if (topIdChilds.isEmpty()){
                userLambdaQueryWrapper.eq(SysUser::getId, loginUser.getId());
            }
            sysUserList = sysUserService.list(userLambdaQueryWrapper);
        }else{
            sysMenus = list();
            sysUserList = sysUserService.list();
        }

        queryWrapper.eq(SysOrgan::getStatus, QueryField.STATU_NOR_);
        List<SysOrgan> organList = sysMenus.stream().sorted(Comparator.comparing(SysOrgan::getSort,Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        List<SysOrgan> menus = buildTreeAndUser(organList);
        return menus;
    }

    @Override
    public List<String> getTopIds(List<String> idList) {
        if (idList == null || idList.size() == 0){
            return new ArrayList<>();
        }
        return sysOrganMapper.getTopIds(idList);
    }

    @Override
    public List<String> getTopIdChilds(List<String> idList) {
        if (idList == null || idList.size() == 0){
            return new ArrayList<>();
        }
        return sysOrganMapper.getTopIdChilds(idList);
    }
    @Override
    public List<String> getIdChilds(List<String> idList) {
        if (idList == null || idList.size() == 0){
            return new ArrayList<>();
        }
        return sysOrganMapper.getIdChilds(idList);
    }


    /**
     * 把list转成树形结构的数据
     */
    private List<SysOrgan> buildTree(List<SysOrgan> collect) {
        List<SysOrgan> finalMenus = new ArrayList<>();
        for (SysOrgan menu : collect) {
            // 先寻找各自的孩子
            for (SysOrgan e : collect) {
                if (e != null && menu != null && e.getParentId().equals(menu.getId())) {
                    menu.getChildren().add(e);
                }
            }
            // 提取出父节点
            if (menu != null && menu.getParentId().equals("0")) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }
    /**
     * 把list转成树形结构的数据
     */
    private List<SysOrgan> buildTreeAndUser(List<SysOrgan> collect) {
        List<SysOrgan> finalMenus = new ArrayList<>();
        Map<String, SysOrgan> organMap = collect.stream().collect(Collectors.toMap(SysOrgan::getId, organ -> organ));

        // 构建组织结构树
        for (SysOrgan menu : collect) {
            if (StringUtils.isBlank(menu.getUserId())){
                menu.setUserId(menu.getId());
            }
            SysOrgan parent = organMap.get(menu.getParentId());
            if (parent != null) {
                parent.getChildren().add(menu);
            } else {
                finalMenus.add(menu);
            }
        }

        // 记录所有有组织的用户ID
        Set<String> organizedUserIds = new HashSet<>();

        // 遍历所有组织，查询其关联的用户
        for (SysOrgan menu : collect) {
            if (StringUtils.isBlank(menu.getUserId())){
                menu.setUserId(menu.getId());
            }
            LambdaQueryWrapper<SysUserOrgan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserOrgan::getOrganId, menu.getId());
            List<SysUserOrgan> userOrgans = sysUserOrganService.list(queryWrapper);

            if (CollectionUtils.isNotEmpty(userOrgans)) {
                List<SysOrgan> userNodes = userOrgans.stream().map(userOrgan -> {
                    SysOrgan userNode = new SysOrgan();
                    BeanUtils.copyProperties(userOrgan, userNode);
                    SysUser sysUser = sysUserList.stream()
                            .filter(user -> user.getId().equals(userOrgan.getUserId()))
                            .findAny()
                            .orElse(new SysUser());
                    userNode.setId(menu.getId());
                    userNode.setUserId(sysUser.getId());
                    userNode.setName(sysUser.getUsername());
                    userNode.setIcon(sysUser.getAvatar());
                    userNode.setCode(sysUser.getLoginname());
                    organizedUserIds.add(sysUser.getId()); // 记录这个用户已经分配到组织
                    return userNode;
                }).collect(Collectors.toList());

                menu.getChildren().addAll(userNodes);
            }
        }

        // 处理无组织的用户：即未出现在任何组织中的用户
        List<SysOrgan> ungroupedUsers = sysUserList.stream()
                .filter(user -> user.getId() != null && !organizedUserIds.contains(user.getId()))
                .map(user -> {
                    SysOrgan userNode = new SysOrgan();
                    userNode.setUserId(user.getId());
                    userNode.setName(user.getUsername());
                    userNode.setIcon(user.getAvatar());
                    userNode.setCode(user.getLoginname());
                    userNode.setParentId("0"); // 设为根级别
                    return userNode;
                }).collect(Collectors.toList());

        // 把无组织的用户放到最外层
        finalMenus.addAll(ungroupedUsers);

        return finalMenus;
    }

}
